<?php
namespace backend\modules\business\controllers;

use backend\controllers\BaseController;
use common\models\BusRepertory;
use common\models\BusGoodsDec;
use yii\base\Object;
use yii\data\Pagination;
use common\extended\system\Util;
use yii\helpers\Url;
/**
 * 商品出库管理
 * @author     chenxiaolin
 * @date        2016年2月23日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */

class GoodsdecController extends BaseController{
    public function init()
    {
        parent::init();
        $this->getView()->params['controller_name'] = 'repertory';
    }
    /**
     * 商品出库
     * @date: 2016年2月25日 
     * @author: chenxiaolin
     */
    public function actionRepertoryout(){
        //获取session中的临时数据
        $session = \Yii::$app->session;
        if(!$this->request->isPost){
            $type = $this->request->get('type',0);
            if($type == 1){
                //清空session
                unset($session['repertoryId']);
                unset($session['repertoryNum']);
            }
            $id = '';
            $repertory = [];
            $count = '';
            $where = $this->where;
            //商品编号
            if(!empty($session['repertoryId'])){
                $idArr = $session['repertoryId'];
                $id = implode(',', $idArr);
            }
            if(!empty($id)){
                $where[] = "repertory_id in ($id)";
                $whereStr = implode ( ' and ', $where );
                $repertory = BusRepertory::find()->where($whereStr)->asArray()->all();
                if(!empty($session['repertoryNum'])){
                    $incnumArr = $session['repertoryNum'];
                    foreach ($repertory as $rk => $rv){
                        foreach ($incnumArr as $ik => $iv){
                            if($rv['repertory_id'] == $iv['id']){
                                array_push($repertory[$rk],$iv['num']);
                            }
                        }
                    }
                }
                $count = BusRepertory::find()->where($whereStr)->count();
            }
            return $this->render('repertoryout',[
                'repertory' => $repertory,
                'count' => $count
            ]);
        }
        //生成标识号
        $user = $this->userInfo;
        $uniqueNum = Util::getSerialNumber($user->uid);
        //获取数据
        $repertory_id = $this->request->post('repertory_id');
        $goods_sell_price = $this->request->post('goods_sell_price');
        $goods_name = $this->request->post('goods_name');
        $goods_specs = $this->request->post('goods_specs');
        $repertory_count = $this->request->post('repertory_count');
        $dec_count = $this->request->post('dec_count');
        for($j=0;$j<count($dec_count);$j++){
            if(empty($dec_count[$j])){
                $this->error('请输入出库数量');
            }
        }
        $supplier_name = $this->request->post('supplier_name');
        $dec_type = $this->request->post('dec_type');
        $dec_remark = $this->request->post('dec_remark');
        //保存数据并修改库存量
        //开启事务
        $transAction = \Yii::$app->db->beginTransaction();
        try {
            for($i=0;$i < count($repertory_id);$i++){
                //修改商品信息
                $where = $this->where;
                $where[] = 'repertory_id = :id';
                $bind[':id'] = $repertory_id[$i];
                $whereStr = implode ( ' and ', $where );
                $repertoryOne = BusRepertory::find()->where($whereStr,$bind)->one();
                //修改库存量
                $repertoryOne->repertory_count = $repertoryOne->repertory_count - $dec_count[$i];
                $repertoryOne->save(false);
                //保存出库数据
                $goodsDec = new BusGoodsDec();
                $goodsDec->dec_type = $dec_type;
                $goodsDec->dec_count = $dec_count[$i];
                $goodsDec->goods_name = $goods_name[$i];
                $goodsDec->supplier_name = $supplier_name[$i];
                $goodsDec->dec_remark = $dec_remark;
                $goodsDec->dec_time = date('Y-m-d H:i:s');
                $goodsDec->shop_id = $user->shop_id;
                $goodsDec->boss_id = $user->boss_uid;
                $goodsDec->unique_flag = $uniqueNum;
                $goodsDec->goods_specs = $goods_specs[$i];
                $goodsDec->repertory_count = $repertoryOne->repertory_count;
                $goodsDec->goods_sell_price = $goods_sell_price[$i];
                $goodsDec->repertory_id = $repertory_id[$i];
                $goodsDec->save(false);
            }
            //清空session
            unset($session['repertoryId']);
            unset($session['barCode']);
            //提交
            $transAction->commit();
            $this->redirect(Url::toRoute(['repertory/repertorymanage']));
        } catch (\Exception $e) {
            //回滚
            $transAction->rollBack();
            $this->error('出库失败！');
        }
        
        //return $this->render('repertoryout');
    }
    
    
    
    /**
     * 出库流水
     * @date: 2016年2月26日
     * @author: chenxiaolin
     */
    public function actionDecrecord(){
        $start_time = $this->request->get('start_time');
        $end_time = $this->request->get('end_time');
        $dec_type = intval($this->request->get('dec_type',-10000));
        $where = $this->where;
        $bind = [];
        //筛选条件
        if($start_time != ''){
            $where[] = 'dec_time >= :starttime';
            $bind[':starttime'] = $start_time.' 00:00:00';
        }
        if($end_time != ''){
            $where[] = 'dec_time <= :endtime';
            $bind[':endtime'] = $end_time.' 59:59:59';
        }
        if($dec_type > -10000){
            $where[] = 'dec_type = :type';
            $bind[':type'] = $dec_type;
        }
        $whereStr = implode(' and ', $where);
        $query = BusGoodsDec::find()->where($whereStr,$bind)->groupBy('unique_flag');
        //分页
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $this->pageNavLimit]);
        $list = $query->offset($pages->offset)->limit($pages->limit)->orderBy('dec_time desc')->asArray()->all();
    
        $i = 0;
        $data = [];
        foreach ($list as $k => $v){
            //根据标识号查询同批出库商品
            $unique_flag = $v['unique_flag'];
            $query = BusGoodsDec::find()->where("unique_flag = $unique_flag");
            //共计数量
            $count = $query->sum('dec_count');
            //日期
            $date = $v['dec_time'];
            //类型
            $type = $v['dec_type'];
            //出库明细
            $record = $query->asArray()->all();
            $str = [];
            foreach ($record as $k => $v){
                $str[$k] = $v['goods_name'].$v['goods_specs'].'('.$v['dec_count'].')';
                $strs = implode(',', $str);
            }
    
            $data[$i] = [
                'unique_flag' => $unique_flag,
                'count' => $count,
                'date' => $date,
                'type' => $type,
                'record' => $str
            ];
            $i++;
        }
        return $this->render('decrecord',[
            'data' => $data,
            'page' => $pages,
            'type' => $dec_type,
            'start_time' => $start_time,
            'end_time' => $end_time
         ]);
    }
    /**
     * 出库详情
     * @date: 2016年2月26日
     * @author: chenxiaolin
     */
    public function actionDecrecorddetal(){
        $this->layout = "/alert";
        //去掉调试栏
        $this->disableDebugtool();
        $unique_flag = $this->request->get('unique_flag');
        $where = $this->where;
        $where[] = 'unique_flag = :flag';
        $bind[':flag'] = $unique_flag;
        $whereStr = implode(' and ', $where);
    
        $data = BusGoodsDec::find()->where($whereStr,$bind)->all();
        //备注信息、出库类型
        $remark = '';
        $type = '';
        foreach ($data as $k){
            $remark = $k['dec_remark'];
            $type = $k['dec_type'];
        }
        return $this->render('decrecorddetal',[
            'data' => $data,
            'remark' => $remark,
            'type' => $type,
        ]);
    }
    /**
     * 导出出库Excel
     * @date: 2016年2月27日
     * @author: chenxiaolin
     */
    public function actionDecexcel(){
        //创建一个excel
        $objPHPExcel = new \PHPExcel();
        //创建新的内置表
        $objPHPExcel->createSheet();
        //设置活动sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //获取当前活动sheet
        $objSheet = $objPHPExcel->getActiveSheet();
        //设置title
        $objSheet->setCellValue('A1','商品名称')->setCellValue('B1','规格')
        ->setCellValue('C1','库存')->setCellValue('D1','出库数量')
        ->setCellValue('E1','供应商')->setCellValue('F1','零售价');
        //获取数据
        $where = $this->where;
        $whereStr = implode(' and ', $where);
        $repertoryDec = BusGoodsDec::find()->where($whereStr)->asArray()->all();
        $i = 2;
        foreach ($repertoryDec as $k => $v){
            $objSheet->setCellValue('A'.$i,$v['goods_name'])->setCellValue('B'.$i,$v['goods_specs'])
            ->setCellValue('C'.$i,$v['repertory_count'])->setCellValue('D'.$i,$v['dec_count'])
            ->setCellValue('E'.$i,$v['supplier_name'])->setCellValue('F'.$i,$v['goods_sell_price']);
            $i++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        Util::browser_export('Excel5','repertoryDec.xls');//输出到浏览器
        $objWriter->save("php://output");
    }
}